package com.zjp.blog.controller.manage;

import com.zjp.blog.controller.BaseController;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


/**
 * @author pj_zhong
 * @email pj_zhong@163.com / pj_zhong@gmail.com
 */
@Controller
@RequestMapping("/manage/file")
public class FileUpload extends BaseController
{
    private static final Logger logger = LogManager.getLogger(FileUpload.class);
    private static String imagesFile = "/resources/images";


    /**
     * Simditor ajax to upload images
     * */
    @RequestMapping(value = "upload",method = RequestMethod.POST)
    @ResponseBody
    public String uploadMultipleFileHandler(@RequestParam("fileData") MultipartFile file)
    {
        String rootPath = getSession().getServletContext().getRealPath(imagesFile);

        File dir = new File(rootPath);
        if(!dir.exists())
            dir.mkdir();

        String result = "{\"success\":result,\"file_path\":\"file_name\"}";
        try{
            if(!file.isEmpty()) {
                File serverFile = new File(rootPath+ File.separator + file.getOriginalFilename());
                file.transferTo(serverFile);

                result=result.replaceFirst("result", "true");
                result=result.replaceFirst("file_name", getRequest().getContextPath() + imagesFile + "/" + file.getOriginalFilename());
                logger.info("Upload Success:" + serverFile.getAbsoluteFile());
            }else {
                result=result.replaceFirst("result","false");
                logger.error("Upload failed: File is Empty");
            }
        }catch (IOException e) {
            logger.error("Upload failed: File is Empty"+ e.getMessage());
        }

        return result;
    }
}
